<template>
  <div class="passwordUpdate">
    <div class="mains_contain">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="租户">
          <el-select v-model="searchForm.tenantId" style="width: 100%" clearable placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备标识">
          <el-input v-model="searchForm.nodeId" clearable placeholder="请输入设备标识" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" clearable placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择设备状态">
            <el-option label="在线" value="ONLINE"></el-option>
            <el-option label="离线" value="OFFLINE"></el-option>
            <el-option label="未注册" value="INACTIVE"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="节点类型">
          <el-select v-model="searchForm.nodeType" clearable placeholder="请选择节点类型">
            <el-option label="终端设备" value="ENDPOINT"></el-option>
            <el-option label="网关设备" value="GATEWAY"></el-option>
            <el-option label="未知设备" value="UNKNOW"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" @click="search" size="mini" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSyn2()" size="mini" icon="el-icon-search" v-has="['password:batch']">批量修改</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" :data="tableData" :max-height="maxHeight" style="width: 100%" @selection-change="handleSelectionChange" fit border stripe size="mini" highlight-current-row
        :header-cell-style="{ background: '#e5e5e5', color: '#000' }" :row-key="bindKey">
        <el-table-column type="selection" label="全选" width="40" :reserve-selection="true" />
        <el-table-column prop="tenantTxt" label="租户名称" width="150" align="center"/>
        <el-table-column prop="esn" label="设备标识" show-overflow-tooltip align="center"/>
        <el-table-column prop="name" label="设备名称" show-overflow-tooltip align="center"/>
        <el-table-column prop="model" label="型号" align="center" min-width="160"/>
        <el-table-column prop="version" label="设备版本" align="center" min-width="160"/>
        <el-table-column prop="state" label="设备状态" align="center">
          <template slot-scope="scope">
            <!-- <el-tag effect="dark" size="mini" type="success" v-if="scope.row.state == 'ONLINE'">在线</el-tag>
          <el-tag effect="dark" size="mini" type="danger" v-if="scope.row.state == 'OFFLINE'">离线</el-tag>
          <el-tag effect="dark" size="mini" type="warning" v-if="scope.row.state == 'INACTIVE'">未注册</el-tag> -->
            <span style="color:#E6A23C" v-if="scope.row.state == 'INACTIVE'">未注册</span>
            <span style="color:#67C23A" v-if="scope.row.state == 'ONLINE'">在线</span>
            <span style="color:#F56C6C" v-if="scope.row.state == 'OFFLINE'">离线</span>
            <span style="color:#F56C6C" v-if="scope.row.state == 'WARNING'">告警</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" size="mini" @click="onSyn(scope.row)" v-has="['password:update']">密码修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
      </div>
    </div>
    <el-dialog title="密码修改" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false" @close="cancle">
      <el-form ref="form" :model="form" label-width="100px" size="small" :rules="rules">
        <el-form-item label="设备用户名" prop="name">
          <!-- <el-input v-model="form.form" clearable /> -->
          <el-select v-model="form.name" style="width: 360px" clearable placeholder="请选择">
            <el-option :label="item.label" v-for="item in options" :value="item.label" :key="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="form.password" clearable @input="changes" />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="submitForm('form')" size="small">保存</el-button>
        <el-button @click="cancle" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "@/utils/index";

import * as api from "@/api/link/device";
import * as apiGroupDevice from "@/api/link/deviceGroup";
import * as apiDownRecord from "@/api/link/downRecord";
import { Message } from "element-ui";
import elTableInfiniteScroll from "el-table-infinite-scroll";
import * as tenantApi from "@/api/sys/tenant";
import { passwords, cnPhone, account, noUpperCasePasswords } from "@/utils/validate";

export default {
  directives: {
    "el-table-infinite-scroll": elTableInfiniteScroll,
  },
  comments: {},
  props: {},
  data() {
    return {
      options: [
        {
          name: "dgri",
          label: "dgri",
        },
        {
          name: "admin",
          label: "admin",
        },
      ],
      tenantList: [],
      isBatch: 0, //0 单个 1 多个
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      curRemark: "重启",
      searchForm: {
        nodeType:"GATEWAY"
      },
      searchTime: [],
      groupList: [],
      multipleSelection: [],
      tableData: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      form: {
        type: "UserAdd",
        tenantId: "",
        name: "",
        password: "",
      },
      dialogVisible: false,
      rules: {
        name: [
          { required: true, message: "必须输入设备用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: this.validatePass, trigger: "blur" },
        ],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
      },
      autoInterval: null,
      autoTimeOut: null,
      scrollNum: 1,
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
  },
  watch: {
    // scrollNum(newVal, oldVal) {
    // }
  },
  created() {
    // this.groupPage();
    this.getPageList();
    this.getTenantList();
  },
  mounted() { },
  methods: {
    bindKey(row) {
      return row.deviceId;
    },
    validatePass(rule, value, callback) {
      if (!noUpperCasePasswords(value)) {
        callback(
          new Error("必须包含小写字母、数字、特殊字符长度在8-16位之间!!")
        );
      } else {
        callback();
      }
    },
    changes(val) {
      this.form.password = val.replace(/\s+/g, "")
    },
    //关闭弹窗
    cancle() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
      this.form.name = "";
      this.form.password = "";
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    // 复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getPageList(limit) {
      console.log(limit);
      this.searchList();
    },
    search() {
      this.pagination.page = 1;
      this.searchList();
    },
    searchList() {
      const p = Object.assign(this.searchForm, this.pagination);
      // if (this.searchTime && this.searchTime.length > 0) {
      //   p.startTime = this.searchTime[0];
      //   p.endTime = this.searchTime[1];
      // } else {
      //   p.startTime = "";
      //   p.endTime = "";
      // }

      api.pagePassWordUpdate(p).then((resp) => {
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    onModifiy() {
      // if (!this.multipleSelection.length) {
      //   this.$message({
      //     type: "warning",
      //     message: "请选择要修改的数据!",
      //   });
      //   return;
      // }
      this.$refs.form.validate((valid) => {
        if (valid) {
          var list = [];
          this.multipleSelection.map((item) => {
            list.push({
              clientId: item.deviceId,
              nodeId: item.esn,
              tenantId: item.tenantId,
            });
          });
          var parmas = Object.assign({}, this.form);
          var p = {
            type: "UserAdd",
            iotDevices: list,
            name: parmas.name,
            password: parmas.password,
            taskId: "1234",
            tenantId: parmas.tenantId,
          };
          apiDownRecord.save(p).then((res) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.search();
            this.dialogVisible = false;
            this.$refs.multipleTable.clearSelection();
          });
        }
      })
    },
    onSyn(row) {
      this.dialogVisible = true;
      this.form.nodeId = row.esn;
      this.form.deviceId = row.deviceId;
      this.form.type = "UserAdd";
      this.form.tenantId = row.tenantId;
    },
    onSyn2() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: "warning",
          message: "请选择要修改的数据!",
        });
        return;
      }
      var tenantIdList = [];
      this.multipleSelection.map((item) => {
        tenantIdList.push(item.tenantId);
      });
      var newArr = Array.from(new Set(tenantIdList));
      if (newArr.length > 1) {
        this.$message.error("不能选择多个租户！！");
        return;
      }
      this.dialogVisible = true;
      this.form.type = "UserAdd";
      this.form.tenantId = newArr[0];
    },
    submitForm(formName) {
      if (this.multipleSelection.length > 0) {
        this.onModifiy();
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var parmas = Object.assign({}, this.form);
            var p = {
              iotDevices: [
                {
                  clientId: parmas.deviceId,
                  nodeId: parmas.nodeId,
                  tenantId: parmas.tenantId,
                },
              ],
              type: "UserAdd",
              name: parmas.name,
              password: parmas.password,
              taskId: "1234",
              tenantId: parmas.tenantId,
            };
            apiDownRecord.save(p).then((res) => {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.search();
              this.dialogVisible = false;
              this.form.name = "";
              this.form.password = "";
              this.$refs.multipleTable.clearSelection();
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
  },
  destroyed() {
    if (this.autoInterval) {
      clearInterval(this.autoInterval);
    }
    if (this.autoTimeOut) {
      clearTimeout(this.autoTimeOut);
    }
  },
};
</script>

<style scoped lang="scss">
.passwordUpdate {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}

.showPo {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0;
  left: 0;
  z-index: 9;
}
.showPo > div {
  width: 300px;
  background: white;
  padding-bottom: 20px;
  border-radius: 20px;
}
.showPo div {
  font-size: 12px;
}

.bg1 {
  display: flex;
  align-content: center;
  align-items: center;
  justify-items: center;
  justify-content: center;
  position: relative;
}
.aaa-bgg {
  margin-top: 20px;
  background-image: url("../../assets/images/13.gif");
  width: 250px;
  height: 115px;
  background-size: 100% 100%;
}
.poBtnC {
  margin-top: 30px;
  display: flex;
  align-content: center;
  align-items: center;
  justify-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.poBtn {
  width: 120px;
  border-radius: 20px;
  background: #3267d5;
  color: white;
  height: 35px;
  line-height: 35px;
  cursor: pointer;
}
.showPo_tip {
  .showPo_tip_one {
    font-size: 22px;
    color: #323232;
  }
  .showPo_tip_two {
    margin-top: 25px;
    font-size: 18px;
    color: #3267d5;
  }
}
</style>
